/*
 * This file is part of FlashLogger, http://code.google.com/p/flashlogger
 *
 * By: Thom Porter
 * Copyright (c) 2009 Thom Porter, www.thomporter.com

 * Released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function()
{
	var instances = [];
	function el(id) {
		return document.getElementById(id);
	}
	var options = extend({
			autoLoad:false,
			forceConsole:false,
			shortcutKey:'c'
		}, window.$FLOptions || {}
	);

	// stripped from jQuery, thanks John Resig - http://jquery.com
	function each(obj, fn) {
		if (!obj) { return; }

		var name, i = 0, length = obj.length;

		// object
		if (length === undefined) {
			for (name in obj) {
				if (fn.call(obj[name], name, obj[name]) === false) { break; }
			}

		// array
		} else {
			for (var value = obj[0];
				i < length && fn.call( value, i, value ) !== false; value = obj[++i]) {
			}
		}

		return obj;
	}

	function extend(o1, o2, sf)
	{
		if (typeof o2 != 'object') { return o1; }

		if (o1 && o2) {
			each(o2, function(k, v) {
				if (!sf || typeof v != 'function') {
					o1[k] = v;
				}
			});
		}

		return o1;
	}

	// event listeners
	function addListener(target,type,callback,captures) {
	    if (target.addEventListener) {
	        target.addEventListener(type,callback,captures);
	    } else if (target.attachEvent) {
	        target.attachEvent('on'+type,callback,captures);
	    } else {
	    	target['on'+type] = callback;
	    }
	}

	// add a listener to open/close the console.
	addListener(document,'keyup',keyListener);

	function keyListener(e)
	{
		e = window.event || e;
		var c,code;
		if (e.keyCode) code = e.keyCode
		else if (e.which) code = e.which
		c = String.fromCharCode(code).toLowerCase();
		if (c==$FL().getOptions().shortcutKey.toLowerCase() && e.shiftKey)
		{
			var opened = !$FL().isConsoleOpened();
			$FL().consoleOpened(opened);
			if (opened) {
				if ($FL().isConsoleIncluded())
				{
					$FLC.show();
				} else {
					$FLCInclude(opened);
				}
			}
			else {
				$FLC.hide();
			}
		} else if (code==27) { // esc
			$FLC.hide();
		}
	}

	var consoleIncluded = false,
		consoleOpened = options.autoLoad;

	// create a class we can intantiate for each log instance...
	function Logger(id)
	{
		if (id == undefined) { id = '_FLCMainLogger'; }
		var self = this;
		var instance_id = id;
		var _isOn = false;

		extend(self, {
			consoleIncluded: function() { consoleIncluded = true; },
			isConsoleIncluded: function() { return consoleIncluded; },
			consoleOpened: function(isOpen) { consoleOpened = isOpen; },
			isConsoleOpened: function() { return consoleOpened; },
			setOptions: function(opts) {
				options = extend(options,opts);
			},
			getOptions: function() {
				return options;
			},
			log : function() {
				if (self._isOn) {
					if (options.forceConsole || self.isConsoleIncluded()) {
						if (arguments.length == 1) $FLC.log(instance_id, arguments[0]);
						else $FLC.log(instance_id, arguments[0],arguments[1]);
					} else {
						if (arguments.length == 1) console.log(arguments[0]);
						else console.log(arguments[0],arguments[1]);
					}
				}
				return self;
			},
			debug : function() {
				if (self._isOn) {
					if (options.forceConsole || self.isConsoleIncluded()) {
						if (arguments.length == 1) $FLC.debug(instance_id, arguments[0]);
						else $FLC.debug(instance_id, arguments[0],arguments[1]);
					} else {
						if (arguments.length == 1) console.debug(arguments[0]);
						else console.debug(arguments[0],arguments[1]);
					}
				}
				return self;
			},
			warn: function() {
				if (self._isOn) {
					if (options.forceConsole || self.isConsoleIncluded()) {
						if (arguments.length == 1) $FLC.warn(instance_id, arguments[0]);
						else $FLC.warn(instance_id, arguments[0],arguments[1]);
					} else {
						if (arguments.length == 1) console.warn(arguments[0]);
						else console.warn(arguments[0],arguments[1]);
					}
				}
				return self;
			},
			error: function() {
				if (self._isOn) {
					if (options.forceConsole || self.isConsoleIncluded()) {
						if (arguments.length == 1) $FLC.error(instance_id, arguments[0]);
						else $FLC.error(instance_id, arguments[0],arguments[1]);
					} else {
						if (arguments.length == 1) console.error(arguments[0]);
						else console.error(arguments[0],arguments[1]);
					}
				}
				return self;
			},
			info: function() {
				if (self._isOn) {
					if (options.forceConsole || self.isConsoleIncluded()) {
						if (arguments.length == 1) $FLC.info(instance_id, arguments[0]);
						else $FLC.info(instance_id, arguments[0],arguments[1]);
					} else {
						if (arguments.length == 1) console.info(arguments[0]);
						else console.info(arguments[0],arguments[1]);
					}
				}
				return self;
			},
			on: function() { self._isOn=true; return self; },
			off: function() {self._isOn=false; return self; },
			isOn: function() { return self._isOn; },
			// just a function flash can use to be sure $FL is loaded...
			isReady: function() { return true; },
			showConsole: function() {
				self.consoleOpened(true);
				$FLCInclude(true);
			}
		});
		return this;
	}

	window.FlashLogger = window.$FL = function(instance)
	{
		if (instance == undefined || instance == '') instance = '_FLCMainLogger';
		if (instances[instance] == undefined) {
			instances[instance] = new Logger(instance, options);
		}

		return instances[instance];
	};

})();

if ($FL().getOptions().forceConsole || typeof(console) == 'undefined' || typeof(console.firebug) == 'undefined') {
	$FLCInclude();
}

function $FLCInclude()
{
	if (!document.body) {
		window.setTimeout('$FLCInclude();', 250);
	}
	if (!$FL().isConsoleIncluded())
	{
		$FL().consoleIncluded(true);
		if ($FL().getOptions().autoLoad || arguments.length>0 && arguments[0] == true) {
			$FL().consoleOpened(true);
		}
		try {
			var scripts = document.getElementsByTagName('script');
			for (var i=0;i<scripts.length;i++)
			{
				if (scripts[i].src.substr(scripts[i].src.length-14) == 'flashLogger.js')
				{
					var script = document.createElement('script');
					script.type = 'text/javascript';
					script.src = scripts[i].src.substr(0,scripts[i].src.length-3) + 'Console.js';
					document.getElementsByTagName('head')[0].appendChild(script);
					var link = document.createElement('link');
					link.type = 'text/css';
					link.rel = 'stylesheet'
					link.href = scripts[i].src.substr(0,scripts[i].src.length-3) + 'Console.css';
					document.getElementsByTagName('head')[0].appendChild(link);
				}
			}
		} catch(ex) {alert('error:',ex.toString());}
	}
	if (arguments.length>0 && arguments[0]==true) {
		$FL().consoleOpened(true);
		if (window.$FLC) {
			$FLC.show();
		}
	}

	return false;
}